package com.mqz.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mqz.seckill.mapper.OrderMapper;
import com.mqz.seckill.mapper.SeckillOrderMapper;
import com.mqz.seckill.pojo.Order;
import com.mqz.seckill.pojo.SeckillGoods;
import com.mqz.seckill.pojo.SeckillOrder;
import com.mqz.seckill.pojo.User;
import com.mqz.seckill.service.OrderService;
import com.mqz.seckill.service.SeckillGoodsService;
import com.mqz.seckill.service.SeckillOrderService;
import com.mqz.seckill.util.MD5Util;
import com.mqz.seckill.util.UUIDUtil;
import com.mqz.seckill.vo.GoodsVO;
import com.ramostear.captcha.HappyCaptcha;
import com.ramostear.captcha.common.Fonts;
import com.ramostear.captcha.support.CaptchaStyle;
import com.ramostear.captcha.support.CaptchaType;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private SeckillGoodsService seckillGoodsService;
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private SeckillOrderService seckillOrderService;

    @Override
    @Transactional
    public Order seckill(User user, GoodsVO goodsVO) {

        SeckillGoods seckillGoods = seckillGoodsService.getOne((new QueryWrapper<SeckillGoods>().eq("goods_id", goodsVO.getId())));

//        if (seckillGoods.getStockCount() > 0) {

//            seckillGoods.setStockCount(seckillGoods.getStockCount() - 1);
//            seckillGoodsService.updateById(seckillGoods);
//        }
        //加入mysql事务，行锁
        boolean update = seckillGoodsService.update(new UpdateWrapper<SeckillGoods>()
                .setSql("stock_count=stock_count-1")
                .eq("goods_id", goodsVO.getId())
                .gt("stock_count", 0));
        if (!update) {
            return null;
        }


        Long userId = user.getId();
        //创建订单
        Order order = new Order();
        order.setCreateDate(new Date());
        order.setUserId(userId);
        order.setGoodsId(seckillGoods.getGoodsId());
        order.setGoodsPrice(seckillGoods.getSeckillPrice());
        order.setDeliveryAddrId(0L);
        order.setGoodsCount(1);
        order.setGoodsName(goodsVO.getGoodsName());
        order.setStatus(0);
        orderMapper.insert(order);

        SeckillOrder seckillOrder = new SeckillOrder();
        seckillOrder.setGoodsId(goodsVO.getId());
        seckillOrder.setOrderId(order.getId());
        seckillOrder.setUserId(userId);
        seckillOrderService.save(seckillOrder);

        redisTemplate.opsForValue()
                .set("order:" + userId + ":" + goodsVO.getId(), seckillOrder);

        return order;
//        }
//        else {
//            return null;
//        }

    }

    @Override
    public String createToken(User user, Long goodsId) {
        String token = MD5Util.md5(UUIDUtil.uuid());

        redisTemplate.opsForValue().set("seckillToken:" + user.getId() + ":" + goodsId, token, 60, TimeUnit.SECONDS);

        return token;
    }

    @Override
    public Boolean isTokenLegal(User user, Long goodsId, String token) {
        if (user == null || goodsId < 0 || !StringUtils.hasText(token)) {
            return false;
        }
        String legalToken = (String) redisTemplate.opsForValue().get("seckillToken:" + user.getId() + ":" + goodsId);

        return token.equals(legalToken);
    }

    @Override
    public void creatCaptcha(HttpServletRequest request, HttpServletResponse response, User user, Long goodsId) {
        HappyCaptcha.require(request, response)
                .style(CaptchaStyle.ANIM)
                .type(CaptchaType.NUMBER)
                .length(6)
                .width(220)
                .height(80)
                .font(Fonts.getInstance().zhFont())
                .build()
                .finish();
    }

    @Override
    public Boolean isCaptchaLegal(User user, Long goodsId, String captcha) {

        if (user == null || goodsId < 0 || !StringUtils.hasText(captcha)) {
            return false;
        }

        String legalCaptcha = (String) redisTemplate.opsForValue().get("captcha:" + user.getId() + ":" + goodsId);
        legalCaptcha = (legalCaptcha == null) ? "" : legalCaptcha;
        return legalCaptcha.equals(captcha);
    }
}
